<template>
  <el-dialog
    title="数据字典"
    :visible.sync="dialogDicVisible"
    :destroy-on-close="true"
    class="ky-small-dialog"
    width="85%"
    top="8vh"
    :before-close="handleDicClose">
    <section class="flex flex-row justify-start align-center">
      <div>
        <el-input style="width:auto" class="" size="small" v-model="listQuery.dicName" placeholder="请输入字典名称" clearable></el-input>
        <el-input style="width:auto" class="" size="small" v-model="listQuery.dicEname" placeholder="请输入字典值" clearable></el-input>
        <el-select class="" size="small" v-model="listQuery.modelType" placeholder="请选择字段来源" clearable>
          <el-option
            v-for="item in options.modelTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button type="primary" class="mar-l-5" size="small" @click="search" plain><i class="el-icon-search"></i><span class="mar-l-3">搜索</span></el-button>
        <el-button v-permission="'YJYY10002007'" class="" type="primary" size="small" @click="handleAdd"><i class="el-icon-circle-plus"></i><span class="mar-l-3">新增字典</span></el-button>
      </div>
    </section>
    <el-row
      v-loading="loading">
      <el-col :span="formFlag ? 14 : 24">
        <el-table
          size="small"
          :data="tableDic"
          style="width: 100%">
          <el-table-column label="操作" width="180" v-if="$hasPermission(['YJYY10002008','YJYY10002009'])">
            <template slot-scope="scope">
              <el-button type="primary" size="small" v-permission="'YJYY10002008'" @click="handleEdit(scope.$index, scope.row)"><i class="el-icon-edit"></i>编辑</el-button>
              <el-button type="danger" size="small" v-permission="'YJYY10002009'" @click="handleDelete(scope.$index, scope.row)"><i class="el-icon-delete"></i>删除</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="dicName" label="字典名称"> </el-table-column>
          <el-table-column prop="dicEname" label="字典值"></el-table-column>
          <el-table-column prop="modelType" label="字段来源" :formatter="frtModelType"></el-table-column>
          <el-table-column prop="clientMethod" label="来源方法" :formatter="frtClientMethod"></el-table-column>
          <el-table-column prop="controllType" label="控件类型" :formatter="frtControllType"></el-table-column>
        </el-table>
        <paginationCont
          :total="totalCount"
          :page.sync="currentPage"
          :limit.sync="pageSize"
          @pagination="fetchData"
        />
      </el-col>
      <el-col :span="formFlag ? 10 : 0">
        <el-form class="rule-form" ref="form" :model="ruleForm" :rules="rules" style="margin-top:40px">
          <el-form-item label="字段中文" label-width="110px" prop="dicName">
            <el-input size="small" v-model="ruleForm.dicName" clearable></el-input>
          </el-form-item>
          <el-form-item label="字段英文" label-width="110px" prop="dicEname">
            <el-input size="small" v-model="ruleForm.dicEname" clearable></el-input>
          </el-form-item>
          <el-form-item label="控件类型" label-width="110px" prop="controllType">
            <el-select
              style="width:100%"
              size="small"
              v-model="ruleForm.controllType"
              placeholder="请选择规则字典的字段"
              clearable
              @change="controllTypeChange">
              <el-option
                v-for="item in options.dicControlTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="字段来源" label-width="110px" prop="modelType">
            <el-select style="width:100%" size="small" v-model="ruleForm.modelType" placeholder="请选择规则字段来源" clearable>
              <el-option
                v-for="item in options.modelTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据来源方法" label-width="110px" prop="clientMethod">
            <el-select
              :disabled="clientMethodByArr.indexOf(ruleForm.controllType) < 0"
              style="width:100%"
              size="small"
              v-model="ruleForm.clientMethod"
              placeholder="请选择数据来源方法"
              filterable
              clearable>
              <el-option
                v-for="item in dicOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="addDic('form')" class="floatR marginL">{{ruleForm.id ? '修改' : '添加'}}</el-button>
            <el-button size="small" @click="cancelAdd" class="floatR m-l-1">取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleDicClose">关 闭</el-button>
      <!-- <el-button size="small" type="primary" @click="handleDicConfirm">确 定</el-button> -->
    </span>
  </el-dialog>
</template>
<script>
import { getItemDicPages, deleteItemDicdmb, addItemDicdmb, editItemDicdmb, getTypeGroupList } from '@/api/api.js'
import paginationCont from '@/components/Pagination/index'
import getDicOptions from '@/mixin/getDicOptions'
import { Options } from '@/utils/constant'

export default {
  name: 'DicDialog',
  mixins: [getDicOptions],
  components: {
    paginationCont
  },
  props: {
    dialogDicVisible: {
      type: Boolean,
      default: false
    },
    hospitalCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      options: Options,
      loading: false,
      listQuery: {
        modelType: null,
        dicName: '',
        dicEname: ''
      },
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      tableDic: [],
      formFlag: false,
      ruleForm: {
        hospitalCode: '',
        dicName: '',
        dicEname: '',
        controllType: '',
        clientMethod: '',
        modelType: 1
      },
      rules: {
        dicName: [{ required: true, message: '请输入字段中文', trigger: 'blur' }],
        dicEname: [{ required: true, message: '请输入字段英文', trigger: 'blur' }],
        controllType: [{ required: true, message: '请选择控件类型', trigger: 'blur' }],
        clientMethod: [{ required: true, message: '请选择数据来源方法', trigger: 'blur' }],
        modelType: [{ required: true, message: '请选择字段来源', trigger: 'blur' }]
      },
      clientMethodByArr: ['3', '5'],
      dicOptions: Options.dicFunction
    }
  },
  watch: {
    dialogDicVisible: {
      immediate: true,
      handler(val) {
        if (val) {
          this.ruleForm.hospitalCode = this.hospitalCode
          this.getType()
          this.fetchData()
        }
      }
    }
  },
  beforeDestroy() {
    this.timeout01 && clearTimeout(this.timeout01)
  },
  methods: {
    search() {
      this.currentPage = 1
      this.fetchData()
    },
    fetchData() {
      this.listQuery.pageSize = this.pageSize
      this.listQuery.pageNumber = this.currentPage
      this.listQuery.modelType = this.listQuery.modelType || null
      this.listQuery.hospitalCode = this.hospitalCode
      // this.tableDic = []
      // this.totalCount = 0
      this.loading = true
      getItemDicPages(this.listQuery).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.tableDic = res.content.list
          this.totalCount = res.content.totalCount
        }
      })
    },
    handleDicClose() {
      this.$emit('myClose')
    },
    handleEdit(i, row) {
      this.formFlag = true
      this.ruleForm = { ...row }
    },
    handleDelete(i, row) {
      this.$confirm('此操作将永久删除该字典, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteData(row)
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    deleteData(row) {
      // 清空右边
      let data = {
        id: row.id,
        hospitalCode: this.hospitalCode
      }
      this.loading = true
      deleteItemDicdmb(data).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.fetchData()
          this.$message.success('删除成功')
          // this.handleReset()
        }
      })
    },
    handleAdd() {
      this.formFlag = true
      this.handleReset()
    },
    addDic(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 修改
          if (this.ruleForm.id) {
            this.loading = true
            editItemDicdmb({ ...this.ruleForm, hospitalCode: this.hospitalCode }).then(res => {
              this.loading = false
              if (res && res.code === 10000) {
                this.fetchData()
                this.$message.success('修改成功')
                // this.handleReset()
              }
            })
          } else {
            this.loading = true
            addItemDicdmb({ ...this.ruleForm, hospitalCode: this.hospitalCode }).then(res => {
              this.loading = false
              if (res && res.code === 10000) {
                this.fetchData()
                this.$message.success('添加成功')
                this.handleReset()
              }
            })
          }
        } else {
          this.timeout01 = setTimeout(() => {
            var isError = document.getElementsByClassName('is-error')
            isError[0].querySelector('input').focus()
          }, 100)
        }
      })
    },
    handleReset() {
      this.ruleForm = {
        hospitalCode: this.hospitalCode,
        dicName: '',
        dicEname: '',
        remark: '',
        clientMethod: '',
        modelType: 1
      }
    },
    cancelAdd() {
      this.formFlag = false
    },
    controllTypeChange(val) {
      console.log(val)
      if (this.clientMethodByArr.indexOf(val) < 0) {
        this.ruleForm.clientMethod = 'getDefault'
      }
    },
    // 获取数据字典，类型
    getType() {
      const params = {
        HospitalCode: this.hospitalCode
      }
      getTypeGroupList(params).then(res => {
        if (res && res.code === 10000) {
          const dic = res.content.list
          let dicArr = []
          dic.forEach(item => {
            dicArr.push({
              value: this.mx_DICKEY + item,
              label: item
            })
          })
          this.dicOptions = dicArr.concat(Options.dicFunction)
        }
      })
    },
    frtModelType(r, c, v, i) {
      const Obj = this.options.modelTypeOptions.find(item => item.value === v)
      return Obj ? Obj.label : ''
    },
    frtClientMethod(r, c, v, i) {
      if (v.indexOf(this.mx_DICKEY) >= 0) {
        return v.replace(this.mx_DICKEY, '')
      }
      const Obj = this.options.dicFunction.find(item => item.value === v)
      return Obj ? Obj.label : ''
    },
    frtControllType(r, c, v, i) {
      const Obj = this.options.dicControlTypeOptions.find(item => item.value === v)
      return Obj ? Obj.label : ''
    }
  }
}
</script>
<style scoped>
.floatR{
    float:right
}
.marginL{
    margin-left: 10px;
}
</style>
